import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:health_flutter_lib/native/nativechannel.dart';
import 'package:intl/intl.dart';
import 'package:table_calendar/table_calendar.dart';

import '../../base/imageres.dart';
import '../../base/beans/jcring_bean.dart';
import '../../base/constant.dart';
import '../../base/eventbus.dart';
import '../../base/lang.dart';
import '../../base/log.dart';
import '../../base/stringres.dart';
import '../../base/theme.dart';
import '../../database/app_data.dart';
import '../../util/physiological_cycle_count.dart';
import '../../util/string_util.dart';
import '../../util/toast_util.dart';
import '../../views/horizontal_line.dart';
import '../../views/jsw_base_view.dart';

///女性健康生理周期日历
class CycleCalendarPage extends StatefulWidget {
  String userId;
  Map<String, int> periodDataMap;
  final int menstrualTime;
  final int cycleValue;
  final int periodValue;
  final int regularly;
  final int tracking;

  CycleCalendarPage(
      {super.key,
      required this.userId,
      required this.periodDataMap,
      required this.menstrualTime,
      required this.cycleValue,
      required this.periodValue,
      required this.regularly,
      required this.tracking});

  @override
  State<StatefulWidget> createState() {
    return _CycleCalendarPageState();
  }
}

class _CycleCalendarPageState extends State<CycleCalendarPage> {
  static const _tag = '[page_cycle_calendar.dart][_CycleCalendarPageState]';

  StreamSubscription? _bus;

  DateTime _focusedDateTime = DateTime.now();

  ///是否显示经期状态
  bool _isShowMenstrualStatus = true;

  ///经期状态(true 开始 false 结束)
  bool _isMenstrualStatus = true;

  ///经期是否选中
  bool _isMenstrualSelect = true;

  ///最近一次月经的时间戳
  int _menstrualTime = 0;

  ///最近一次月经的DateTime
  DateTime _menstrualDateTime = DateTime.now();

  ///月经周期天数
  var _menstrualPeriodDays = 0;

  ///卵泡期天数
  var _follicularPhaseDays = 0;

  ///易孕前窗期
  var _preFertileLength = 0;

  ///易孕期(排卵期)天数(最多十天)
  var _easyPregnancyDays = 0;

  ///黄体期天数
  var _lutealPhaseDays = 13;

  ///是否显示排卵日
  bool _isShowOvulation = false;

  ///排卵日
  DateTime _ovulationDateTime = DateTime.now();

  ///选中的记录日期
  DateTime _recordDateTime = DateTime.now();

  ///是否有日历的记录
  var _isCalendarRecord = false;

  ///记录的分类
  List<String> _recordPaths = [];
  List<String> _recordItems = [];
  List<bool> _recordLines = [];

  int _flowIndex = -1;
  final List<String> _flowItems = [
   StringRes.very_light,
   StringRes.light,
   StringRes.medium,
   StringRes.heavy,
   StringRes.very_heavy
  ];

  int _colorIndex = -1;
  final List<String> _colorItems = [
   StringRes.light_red,
   StringRes.bright_red,
   StringRes.dark_red,
   StringRes.brown,
   StringRes.black
  ];

  int _dysmenorrheaIndex = -1;
  final List<String> _dysmenorrheaItems = [
   StringRes.no_pain,
   StringRes.mild,
   StringRes.noticeable,
   StringRes.severe,
   StringRes.extreme
  ];

  List<int> _symptomSelected = List.filled(8, 0);
  final List<String> _symptomItems = [
   StringRes.abdominal_pain,
   StringRes.headache,
   StringRes.breast_tenderness,
   StringRes.body_ches,
   StringRes.low_back_pain,
   StringRes.diarrhea,
   StringRes.constipation,
   StringRes.back_pain
  ];

  int _leucorrheaIndex = -1;
  final List<String> _leucorrheaItems = [
   StringRes.sticky,
   StringRes.paste_like,
   StringRes.watery,
   StringRes.egg_white_like
  ];

  int _moodIndex = -1;
  final List<String> _moodItems = [
   StringRes.happy,
   StringRes.calm,
   StringRes.tired,
   StringRes.anxious,
   StringRes.depressed
  ];

  int _ovulationIndex = -1;
  final List<String> _ovulationItems = [
   StringRes.not_ovulated,
   StringRes.ovulated,
  ];

  int _sexIndex = -1;
  final List<String> _sexItems = [
   StringRes.have,
   StringRes.not_have,
  ];

  ///记录的备注信息
  String _notes = " ";

  String _startRecordDay = "";

  String _endRecordDay = "";

  ///经期记录列表
  List<MenstrualRecord> _menstrualRecordList = [];

  String _recordTitle = "";

  ///月经周期时间map
  Map<String, int> _periodDataMap = {};

  ///是否删除
  bool _isDeleteMenstrual = false;

  @override
  void initState() {
    super.initState();
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual,
        overlays: SystemUiOverlay.values);
    _initEventBus();
    _menstrualTime = widget.menstrualTime;
    _menstrualPeriodDays = widget.periodValue;
    _periodDataMap = widget.periodDataMap;
    _initCalculationPeriodData();
    _setMenstrualStatus(DateTime.now());
    APPDatabase.queryHealthRecordData(
            widget.userId, _startRecordDay, _endRecordDay)
        .then((value) {
      _menstrualRecordList = value;
      _setRecordMenstrualData();
    });
  }

  ///初始化EventBus
  void _initEventBus() {
    _bus = EventBusUtil.getInstance().on().listen((event) {
      switch (event.runtimeType) {
        case DataEvent:
          DataEvent dataEvent = event;
          switch (dataEvent.type) {
            case HealthDataType.REFRESH_MENSTRUAL_RECORD_DATA:
              setMenstrualRecordData(dataEvent.data);
              _menstrualRecordList.removeWhere((record) =>
                  record.day ==
                  DateFormat("yyyy-MM-dd").format(_recordDateTime));
              _menstrualRecordList.add(MenstrualRecord(
                  _flowIndex,
                  _dysmenorrheaIndex,
                  _symptomSelected,
                  _leucorrheaIndex,
                  _moodIndex,
                  _ovulationIndex,
                  _sexIndex,
                  _colorIndex,
                  _notes,
                  DateFormat("yyyy-MM-dd").format(_recordDateTime)));
              setState(() {});
              break;
            case HealthDataType.REFRESH_CURRENT_MENSTRUAL_RECORD_DATA:
              setMenstrualRecordData(dataEvent.data);
              setState(() {});
              break;
          }
          break;
      }
    });
  }

  ///取消EventBus订阅
  void _cancelEventBus() {
    _bus?.cancel();
  }

  @override
  void dispose() {
    _cancelEventBus();
    super.dispose();
  }

  ///初始化主界面的周期数据
  void _initCalculationPeriodData() {
    _menstrualDateTime = DateTime.fromMillisecondsSinceEpoch(_menstrualTime);

    final cycleCalculator = CycleCalculator(
        periodStart: _menstrualDateTime,
        cycleLength: widget.cycleValue,
        periodLength: _menstrualPeriodDays);
    final summary = cycleCalculator.summarize();
    Map<String, int> cycleMap = summary.compute();
    _follicularPhaseDays = cycleMap["卵泡期"]!;
    _preFertileLength = cycleMap["易孕前窗"]!;
    _easyPregnancyDays =
        cycleMap["易孕前窗"]! + cycleMap["排卵日"]! + cycleMap["易孕后窗"]!;
    _lutealPhaseDays = cycleMap["黄体期"]!;
    _isShowOvulation = cycleMap["排卵日"]! == 1;
    _ovulationDateTime = _menstrualDateTime.add(Duration(
        days:
            (cycleMap["易孕前窗"]!) + _menstrualPeriodDays + _follicularPhaseDays));

    DartLog.i(_tag,
        '_initCalculationPeriodData 初始化周期天数参数_menstrualTime$_menstrualTime ${DateFormat("yyyy-MM-dd").format(DateTime.fromMillisecondsSinceEpoch(_menstrualTime))} _cycleValue：${widget.cycleValue} _menstrualPeriodDays：${_menstrualPeriodDays} _follicularPhaseDays：$_follicularPhaseDays _easyPregnancyDays：$_easyPregnancyDays _lutealPhaseDays：$_lutealPhaseDays  ');

    DartLog.i(_tag,
        '_initCalculationPeriodData 排卵日期 _ovulationDateTime ${DateFormat("yyyy-MM-dd").format(_ovulationDateTime)} distanceDays ${_menstrualPeriodDays + _follicularPhaseDays + (cycleMap["易孕前窗"]!)}');

    _startRecordDay = DateFormat("yyyy-MM-dd").format(DateTime(2024, 1, 1));
    _endRecordDay = DateFormat("yyyy-MM-dd").format(DateTime.now());
    _recordTitle = _getRecordDayTitle(_recordDateTime);
  }

  ///设置记录的数据
  void _setRecordMenstrualData() {
    bool isRecordData = false;
    for (MenstrualRecord record in _menstrualRecordList) {
      if (record.day == DateFormat("yyyy-MM-dd").format(_recordDateTime)) {
        Map<String, dynamic> dataMap = <String, dynamic>{};
        dataMap['flowIndex'] = record.flowRate;
        dataMap['colorIndex'] = record.colorRate;
        dataMap['dysmenorrheaIndex'] = record.dysmenorrhea;
        dataMap['symptomSelected'] = record.symptoms;
        dataMap['leucorrheaIndex'] = record.leucorrhea;
        dataMap['moodIndex'] = record.mood;
        dataMap['ovulationIndex'] = record.ovulation;
        dataMap['sexIndex'] = record.love;
        dataMap['notes'] = record.notes;
        DartLog.i(_tag, 'dataMap：${dataMap.toString()}');
        isRecordData = true;
        EventBusUtil.getInstance().fire(DataEvent(
            HealthDataType.REFRESH_CURRENT_MENSTRUAL_RECORD_DATA, dataMap));
        break;
      }
    }
    if (!isRecordData) {
      _isCalendarRecord = false;
      _flowIndex = -1;
      _colorIndex = -1;
      _dysmenorrheaIndex = -1;
      _symptomSelected = List.filled(8, 0);
      _leucorrheaIndex = -1;
      _moodIndex = -1;
      _ovulationIndex = -1;
      _sexIndex = -1;
      _notes = "";
      setState(() {});
    }
  }

  void setMenstrualRecordData(Map<String, dynamic> data) {
    _notes = data["notes"];
    _recordPaths.clear();
    _recordItems.clear();
    _recordLines.clear();
    if (_notes.isNotEmpty) {
      _flowIndex = data["flowIndex"];
      _colorIndex = data["colorIndex"];
      _dysmenorrheaIndex = data["dysmenorrheaIndex"];
      final symptomData = data["symptomSelected"];
      if (symptomData is List) {
        _symptomSelected = symptomData.map((e) => e as int).toList();
      }
      _leucorrheaIndex = data["leucorrheaIndex"];
      _moodIndex = data["moodIndex"];
      _ovulationIndex = data["ovulationIndex"];
      _sexIndex = data["sexIndex"];
      _isCalendarRecord = true;
    }
    if (_flowIndex >= 0) {
      _recordPaths.add(ImagePathData.selectedFlowPaths[_flowIndex]);
      _recordItems.add(_flowItems[_flowIndex]);
      _recordLines.add(true);
    }
    if (_colorIndex >= 0) {
      _recordPaths.add(ImagePathData.selectedColorPaths[_colorIndex]);
      _recordItems.add(_colorItems[_colorIndex]);
      _recordLines.add(true);
    }
    if (_dysmenorrheaIndex >= 0) {
      _recordPaths.add(ImagePathData.selectedDysmenorrheaPaths[_dysmenorrheaIndex]);
      _recordItems.add(_dysmenorrheaItems[_dysmenorrheaIndex]);
      _recordLines.add(true);
    }
    if (_symptomSelected.isNotEmpty) {
      for (int i = 0; i < _symptomSelected.length; i++) {
        if (_symptomSelected[i] == 1) {
          _recordPaths.add(ImagePathData.selectedSymptomPaths[i]);
          _recordItems.add(_symptomItems[i]);
          _recordLines.add(false);
        }
      }
    }
    if (_symptomSelected.isNotEmpty && _recordLines.isNotEmpty) {
      _recordLines[_recordLines.length - 1] = true;
    }
    if (_leucorrheaIndex >= 0) {
      _recordPaths.add(ImagePathData.selectedLeucorrheaPaths[_leucorrheaIndex]);
      _recordItems.add(_leucorrheaItems[_leucorrheaIndex]);
      _recordLines.add(true);
    }
    if (_moodIndex >= 0) {
      _recordPaths.add(ImagePathData.selectedMoodPaths[_moodIndex]);
      _recordItems.add(_moodItems[_moodIndex]);
      _recordLines.add(true);
    }
    if (_ovulationIndex >= 0) {
      _recordPaths.add(ImagePathData.selectedOvulationPaths[_ovulationIndex]);
      _recordItems.add(_ovulationItems[_ovulationIndex]);
      _recordLines.add(true);
    }
    if (_sexIndex >= 0) {
      _recordPaths.add(ImagePathData.selectedSexPaths[_sexIndex]);
      _recordItems.add(_sexItems[_sexIndex]);
      _recordLines.add(true);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Container(
          decoration: const BoxDecoration(
            image: DecorationImage(
              image: AssetImage(ImageRes.bg_health_main),
              fit: BoxFit.cover, // 图片填充方式
            ),
          ),
        ),
        Scaffold(
          backgroundColor: Colors.transparent, // 设置 Scaffold 背景透明
          body: SingleChildScrollView(
              child: Column(
            children: [
              AppBar(
                  elevation: 0.0,
                  backgroundColor: Colors.transparent,
                  title: EasyTouch(
                    width: double.infinity,
                    child: Text(
                     StringRes.women_calendar_title,
                      textAlign: TextAlign.center,
                      style: ThemeUtil.toolbar,
                    ),
                  ),
                  leading: IconButton(
                    splashColor: Colors.transparent,
                    highlightColor: Colors.transparent,
                    hoverColor: Colors.transparent,
                    icon: const Icon(
                      Icons.arrow_back,
                      color: Colors.white,
                    ),
                    onPressed: () {
                      Get.back();
                    },
                  ),
                  actions: [
                    TextButton(
                      style: TextButton.styleFrom(
                        side: const BorderSide(
                          width: 1, // 边框宽度
                          color: Colors.white, // 边框颜色
                        ),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(25.0), // 设置按钮圆角
                        ),
                        // 设置内边距，可根据需求调整值
                        padding: const EdgeInsets.symmetric(
                            horizontal: 14, vertical: 4),
                        minimumSize: Size.zero,
                        tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                      ),
                      onPressed: () {
                        //回到今天
                        _focusedDateTime = DateTime.now();
                        _recordDateTime = DateTime.now();
                        _recordTitle = _getRecordDayTitle(_recordDateTime);
                        if (_recordDateTime.millisecondsSinceEpoch <=
                            DateTime.now().millisecondsSinceEpoch) {
                          _setRecordMenstrualData();
                        } else {
                          setState(() {});
                        }
                      },
                      child: Text(StringRes.today,
                          textAlign: TextAlign.center,
                          style: ThemeUtil.toolbar.copyWith(fontSize: 14)),
                    ),
                    const SizedBox(width: 15, height: 0),
                  ]),

              const SizedBox(height: 6),

              //时间选择器
              Container(
                  margin: const EdgeInsets.only(left: 16, right: 16),
                  child: TableCalendar<String>(
                    daysOfWeekHeight: 32.0,
                    locale: S.getCalendarLocale(),
                    firstDay: DateTime.utc(2024, 1, 1),
                    lastDay: DateTime.utc(DateTime.now().year + 1, 12, 31),
                    focusedDay: _focusedDateTime,
                    headerStyle: const HeaderStyle(
                      titleTextStyle: TextStyle(
                          color: Colors.white,
                          fontSize: 18,
                          fontWeight: FontWeight.normal),
                      leftChevronIcon: Icon(
                        Icons.chevron_left,
                        color: Colors.white,
                        size: 30,
                      ),
                      rightChevronIcon: Icon(
                        Icons.chevron_right,
                        color: Colors.white,
                        size: 30,
                      ),
                      titleCentered: true,
                      leftChevronVisible: true,
                      rightChevronVisible: true,
                      formatButtonVisible: false,
                    ),
                    daysOfWeekStyle: const DaysOfWeekStyle(
                      weekdayStyle: TextStyle(color: Colors.white),
                      weekendStyle: TextStyle(color: Colors.white), // 周末的文本样式颜色
                    ),
                    calendarStyle: const CalendarStyle(
                      disabledTextStyle: TextStyle(color: Colors.transparent),
                      outsideTextStyle:
                          TextStyle(color: Colors.transparent), //不属于当月的日期
                    ),
                    onDaySelected: (selectedDay, focusedDay) {
                      _focusedDateTime = selectedDay;
                      _recordDateTime = selectedDay;
                      _recordTitle = _getRecordDayTitle(_recordDateTime);
                      _setMenstrualStatus(_recordDateTime);
                      if (_recordDateTime.millisecondsSinceEpoch <=
                          DateTime.now().millisecondsSinceEpoch) {
                        _setRecordMenstrualData();
                      } else {
                        setState(() {});
                      }
                    },
                    calendarBuilders: CalendarBuilders(
                      selectedBuilder: (context, day, focusedDay) {
                        bool isSameDay = _isSameDay(_recordDateTime, day);
                        return Container(
                          alignment: Alignment.center,
                          margin: const EdgeInsets.symmetric(horizontal: 0),
                          width: double.infinity,
                          height: 48,
                          decoration: BoxDecoration(
                            border: Border.all(
                              width: isSameDay ? 1.5 : 0,
                              color: isSameDay
                                  ? Colors.white
                                  : Colors.transparent,
                            ),
                            // 设置形状为圆形
                            borderRadius: BorderRadius.circular(10.0),
                          ),
                          child: Stack(
                            alignment: Alignment.center,
                            children: [
                              // 背景
                              _getDateTimeBackground(day, isSameDay),

                              _isSetOvulationDay(day)
                                  ? const Image(
                                      image: AssetImage(
                                          ImageRes.ic_calendar_ovulation),
                                      width: 28,
                                      height: 28,
                                    )
                                  : const SizedBox(),

                              _isSetMenstrualPeriodDay(day)
                                  ? const Image(
                                      image: AssetImage(
                                          ImageRes.bg_calendar_period),
                                      width: 24,
                                      height: 30,
                                    )
                                  : const SizedBox(),

                              Positioned(
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  children: [
                                    _isRecordMenstrual(day)
                                        ? Container(
                                            width: 48,
                                            padding: const EdgeInsets.only(
                                                top: 2, right: 2),
                                            alignment: Alignment.topRight,
                                            child: const Image(
                                              image: AssetImage(
                                                  ImageRes.ic_calendar_mark),
                                              width: 7,
                                              height: 7,
                                            ),
                                          )
                                        : const SizedBox(
                                            width: 7,
                                            height: 7,
                                          ),
                                    Text(
                                      day.day.toString(),
                                      textAlign: TextAlign.center,
                                      style:
                                          ThemeUtil.mp2.copyWith(fontSize: 13),
                                    ),
                                    (_isMenstrualStartDay(day) ||
                                            _isMenstrualEndDay(day))
                                        ? Container(
                                            width: 48,
                                            padding: const EdgeInsets.only(
                                                bottom: 2, right: 2),
                                            alignment: Alignment.bottomRight,
                                            child: Image(
                                              image: AssetImage(
                                                  _isMenstrualEndDay(day)
                                                      ? ImageRes
                                                          .ic_calendar_start
                                                      : ImageRes
                                                          .ic_calendar_end),
                                              width: 7,
                                              height: 7,
                                            ))
                                        : const SizedBox(
                                            width: 7,
                                            height: 7,
                                          ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        );
                      }, //选中日期
                      todayBuilder: (context, day, focusedDay) {
                        bool isSameDay = _isSameDay(_recordDateTime, day);
                        return Container(
                          alignment: Alignment.center,
                          margin: const EdgeInsets.symmetric(horizontal: 0),
                          width: 48,
                          height: 48,
                          decoration: BoxDecoration(
                            border: Border.all(
                              width: isSameDay ? 1.5 : 0,
                              color: isSameDay
                                  ? Colors.white
                                  : Colors.transparent,
                            ),
                            borderRadius: BorderRadius.circular(10.0),
                          ),
                          child: Stack(
                            alignment: Alignment.center,
                            children: [
                              // 背景
                              _getDateTimeBackground(day, isSameDay),

                              _isSetOvulationDay(day)
                                  ? const Image(
                                      image: AssetImage(
                                          ImageRes.ic_calendar_ovulation),
                                      width: 28,
                                      height: 28,
                                    )
                                  : const SizedBox(),

                              _isSetMenstrualPeriodDay(day)
                                  ? const Image(
                                      image: AssetImage(
                                          ImageRes.bg_calendar_period),
                                      width: 24,
                                      height: 30,
                                    )
                                  : const SizedBox(),

                              Positioned(
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  children: [
                                    _isRecordMenstrual(day)
                                        ? Container(
                                            width: 48,
                                            padding: const EdgeInsets.only(
                                                top: 2, right: 2),
                                            alignment: Alignment.topRight,
                                            child: const Image(
                                              image: AssetImage(
                                                  ImageRes.ic_calendar_mark),
                                              width: 7,
                                              height: 7,
                                            ),
                                          )
                                        : const SizedBox(
                                            width: 7,
                                            height: 7,
                                          ),
                                    Text(
                                      day.day.toString(),
                                      textAlign: TextAlign.center,
                                      style:
                                          ThemeUtil.mp2.copyWith(fontSize: 13),
                                    ),
                                    (_isMenstrualStartDay(day) ||
                                            _isMenstrualEndDay(day))
                                        ? Container(
                                            width: 48,
                                            padding: const EdgeInsets.only(
                                                bottom: 2, right: 2),
                                            alignment: Alignment.bottomRight,
                                            child: Image(
                                              image: AssetImage(
                                                  _isMenstrualEndDay(day)
                                                      ? ImageRes
                                                          .ic_calendar_start
                                                      : ImageRes
                                                          .ic_calendar_end),
                                              width: 7,
                                              height: 7,
                                            ))
                                        : const SizedBox(
                                            width: 7,
                                            height: 7,
                                          ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        );
                      }, //今天日期
                      defaultBuilder: (context, day, focusedDay) {
                        bool isSameDay = _isSameDay(_recordDateTime, day);
                        return Container(
                          alignment: Alignment.center,
                          margin: const EdgeInsets.symmetric(horizontal: 0),
                          width: 48,
                          height: 48,
                          decoration: BoxDecoration(
                            border: Border.all(
                              width: isSameDay ? 1.5 : 0,
                              color: isSameDay
                                  ? Colors.white
                                  : Colors.transparent,
                            ),
                            borderRadius: BorderRadius.circular(10.0),
                          ),
                          child: Stack(
                            alignment: Alignment.center,
                            children: [
                              // 背景图
                              _getDateTimeBackground(day, isSameDay),

                              _isSetOvulationDay(day)
                                  ? const Image(
                                      image: AssetImage(
                                          ImageRes.ic_calendar_ovulation),
                                      width: 28,
                                      height: 28,
                                    )
                                  : const SizedBox(),

                              _isSetMenstrualPeriodDay(day)
                                  ? const Image(
                                      image: AssetImage(
                                          ImageRes.bg_calendar_period),
                                      width: 24,
                                      height: 32,
                                    )
                                  : const SizedBox(),

                              Positioned(
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  children: [
                                    _isRecordMenstrual(day)
                                        ? Container(
                                            width: 48,
                                            padding: const EdgeInsets.only(
                                                top: 2, right: 2),
                                            alignment: Alignment.topRight,
                                            child: const Image(
                                              image: AssetImage(
                                                  ImageRes.ic_calendar_mark),
                                              width: 7,
                                              height: 7,
                                            ),
                                          )
                                        : const SizedBox(
                                            width: 7,
                                            height: 7,
                                          ),
                                    Text(
                                      day.day.toString(),
                                      textAlign: TextAlign.center,
                                      style:
                                          ThemeUtil.mp2.copyWith(fontSize: 13),
                                    ),
                                    (_isMenstrualStartDay(day) ||
                                            _isMenstrualEndDay(day))
                                        ? Container(
                                            width: 48,
                                            padding: const EdgeInsets.only(
                                                bottom: 2, right: 2),
                                            alignment: Alignment.bottomRight,
                                            child: Image(
                                              image: AssetImage(
                                                  _isMenstrualEndDay(day)
                                                      ? ImageRes
                                                          .ic_calendar_start
                                                      : ImageRes
                                                          .ic_calendar_end),
                                              width: 7,
                                              height: 7,
                                            ))
                                        : const SizedBox(
                                            width: 7,
                                            height: 7,
                                          ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        );
                      }, //默认日期
                    ),
                  )),

              //类型显示布局
              JSWLine(
                clickable: false,
                margin: const EdgeInsets.only(
                    top: 20, left: 50.0, right: 10.0, bottom: 10.0),
                children: [
                  BaseViewItem(
                    weight: 1,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: <Widget>[
                        const Image(
                          image: AssetImage(ImageRes.ic_calendar_period),
                          width: 12,
                          height: 15,
                        ),
                        const SizedBox(
                          height: 10.0,
                          width: 4.0,
                        ),
                        Text(
                         StringRes.menstrual_period,
                          textAlign: TextAlign.center,
                          softWrap: true,
                          style: ThemeUtil.p2.copyWith(
                              fontSize: 14,
                              color:
                                  const Color(ThemeUtil.primaryWhiteValue50)),
                        ),
                      ],
                    ),
                  ),
                  BaseViewItem(
                    weight: 1,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: <Widget>[
                        Container(
                          width: 12,
                          height: 12,
                          decoration: const BoxDecoration(
                            shape: BoxShape.circle,
                            color:
                                Color(ThemeUtil.primarCalendarPredictionValue),
                          ),
                        ),
                        const SizedBox(
                          height: 10.0,
                          width: 4.0,
                        ),
                        Text(
                         StringRes.menstrual_prediction,
                          textAlign: TextAlign.center,
                          softWrap: true,
                          style: ThemeUtil.p2.copyWith(
                              fontSize: 14,
                              color:
                                  const Color(ThemeUtil.primaryWhiteValue50)),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
              JSWLine(
                clickable: false,
                margin: const EdgeInsets.only(left: 50.0, right: 10.0),
                children: [
                  BaseViewItem(
                    weight: 1,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: <Widget>[
                        Container(
                          width: 12,
                          height: 12,
                          decoration: const BoxDecoration(
                            shape: BoxShape.circle,
                            color: Color(ThemeUtil.primarPregnancyValue),
                          ),
                        ),
                        const SizedBox(
                          height: 10.0,
                          width: 4.0,
                        ),
                        Text(
                         StringRes.easy_pregnancy,
                          textAlign: TextAlign.center,
                          softWrap: true,
                          style: ThemeUtil.p2.copyWith(
                              fontSize: 14,
                              color:
                                  const Color(ThemeUtil.primaryWhiteValue50)),
                        ),
                      ],
                    ),
                  ),
                  BaseViewItem(
                    weight: 1,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: <Widget>[
                        const Image(
                          image: AssetImage(ImageRes.ic_calendar_ovulation),
                          width: 12,
                          height: 12,
                        ),
                        const SizedBox(
                          height: 10.0,
                          width: 4.0,
                        ),
                        Text(
                         StringRes.ovulation_day,
                          softWrap: true,
                          textAlign: TextAlign.center,
                          style: ThemeUtil.p2.copyWith(
                              fontSize: 14,
                              color:
                                  const Color(ThemeUtil.primaryWhiteValue50)),
                        ),
                      ],
                    ),
                  ),
                ],
              ),

              //经期开始选择
              _isShowMenstrualStatus
                  ? Container(
                      margin: const EdgeInsets.only(
                          top: 24, left: 20.0, right: 20.0, bottom: 24.0),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: <Widget>[
                          Image(
                            image: AssetImage(_isMenstrualStatus
                                ? ImageRes.ic_menstruation_end
                                : ImageRes.ic_menstruation_start),
                            width: 18,
                            height: 18,
                          ),
                          const SizedBox(
                            height: 10.0,
                            width: 4.0,
                          ),
                          Text(
                            _isMenstrualStatus
                                ?StringRes.menstruation_end
                                :StringRes.menstruation_start,
                            textAlign: TextAlign.center,
                            style: ThemeUtil.mp2.copyWith(fontSize: 14),
                          ),
                          const Spacer(),
                          EasyTouch(
                            height: 40,
                            width: 108,
                            onPressed: () {
                              ///生理周期开始结束点击
                              _setMenstrualClick();
                            },
                            child: Container(
                              height: 40,
                              width: 108,
                              decoration: BoxDecoration(
                                color: const Color(0XFF3F3F3F),
                                borderRadius:
                                    BorderRadius.circular(10.0), // 设置圆角半径
                              ),
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.start,
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: [
                                  Container(
                                      height: 40,
                                      width: 54,
                                      alignment: Alignment.center,
                                      decoration: BoxDecoration(
                                        color: _isMenstrualSelect
                                            ? const Color(
                                                ThemeUtil.primaryBlueValue)
                                            : Colors.transparent,
                                        borderRadius: BorderRadius.circular(
                                            10.0), // 设置圆角半径
                                      ),
                                      child: Text(
                                       StringRes.yes,
                                        textAlign: TextAlign.center,
                                        style:
                                            ThemeUtil.p2.copyWith(fontSize: 13),
                                      )),
                                  Container(
                                      height: 40,
                                      width: 54,
                                      alignment: Alignment.center,
                                      decoration: BoxDecoration(
                                        color: _isMenstrualSelect
                                            ? Colors.transparent
                                            : const Color(
                                                ThemeUtil.primaryBlueValue),
                                        borderRadius: BorderRadius.circular(
                                            10.0), // 设置圆角半径
                                      ),
                                      child: Text(
                                       StringRes.no,
                                        textAlign: TextAlign.center,
                                        style:
                                            ThemeUtil.p2.copyWith(fontSize: 13),
                                      )),
                                ],
                              ),
                            ),
                          ),
                        ],
                      ),
                    )
                  : Container(),

              _recordDateTime.millisecondsSinceEpoch <=
                      DateTime.now().millisecondsSinceEpoch
                  ? (_isCalendarRecord
                      ? Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    //记录列表
                    Container(
                        margin: const EdgeInsets.only(top: 10, bottom: 10),
                        decoration: BoxDecoration(
                          gradient: const LinearGradient(
                            begin: Alignment.topCenter,
                            end: Alignment.bottomCenter,
                            colors: [
                              Color(0XFF1B1D20),
                              Color(0XFF141518)
                            ],
                          ),
                          borderRadius: BorderRadius.circular(20.0), // 设置圆角半径
                        ),
                        child: Column(
                            mainAxisAlignment: MainAxisAlignment.start,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              Container(
                                margin: const EdgeInsets.only(top: 12.0),
                                padding: const EdgeInsets.only(left: 20,right: 20),
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  children: <Widget>[
                                    Text(
                                      StringUtil.getCurrentPeriodTitle(
                                          _recordTitle),
                                      textAlign: TextAlign.center,
                                      style: ThemeUtil.mp2
                                          .copyWith(fontSize: 14),
                                    ),
                                    const Spacer(),
                                    EasyTouch(
                                      padding: const EdgeInsets.only(
                                          top: 20, bottom: 20),
                                      onPressed: () {
                                        _gotoRecordMenstrualPage();
                                      },
                                      child: Row(
                                        mainAxisAlignment:
                                        MainAxisAlignment.start,
                                        crossAxisAlignment:
                                        CrossAxisAlignment.center,
                                        children: [
                                          const Image(
                                            image: AssetImage(
                                                ImageRes.ic_period_edit),
                                            width: 15,
                                            height: 15,
                                          ),
                                          const SizedBox(
                                            width: 10.0,
                                          ),
                                          Text(
                                           StringRes.record,
                                            textAlign: TextAlign.center,
                                            style: ThemeUtil.mp2.copyWith(
                                                color: const Color(ThemeUtil
                                                    .primaryBlueValue)),
                                          ),
                                        ],
                                      ),
                                    ),
                                  ],
                                ),
                              ),

                              _buildCategory(
                                items: _recordItems,
                                iconPaths: _recordPaths,
                                isShowLines: _recordLines,
                              ),

                              const SizedBox(
                                height: 10,
                              )
                            ])),

                    Container(
                        margin: const EdgeInsets.only(top: 10),
                        decoration: const BoxDecoration(
                          gradient: LinearGradient(
                            begin: Alignment.topCenter,
                            end: Alignment.bottomCenter,
                            colors: [
                              Color(0XFF1B1D20),
                              Color(0XFF141518)
                            ],
                          ),
                          borderRadius: BorderRadius.only(topLeft: Radius.circular(20.0),topRight: Radius.circular(20.0)), // 设置圆角半径
                        ),
                        child: Column(
                            mainAxisAlignment: MainAxisAlignment.start,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              Container(
                                width: double.infinity,
                                margin: const EdgeInsets.only(
                                    left: 20.0, top: 10),
                                child: Text(
                                 StringRes.notes_title,
                                  textAlign: TextAlign.left,
                                  style: ThemeUtil.mp2.copyWith(fontSize: 16),
                                ),
                              ),

                              Container(
                                width: double.infinity,
                                constraints: const BoxConstraints(minHeight: 88),
                                margin: const EdgeInsets.only(
                                    left: 20.0,
                                    top: 20,
                                    right: 20.0,
                                    bottom: 30.0),
                                padding: const EdgeInsets.all(10.0),
                                decoration: BoxDecoration(
                                    color: Colors.black,
                                    borderRadius: BorderRadius.circular(10.0)),
                                child: Text(
                                  _notes,
                                  textAlign: TextAlign.left,
                                  style: ThemeUtil.mp2.copyWith(fontSize: 12),
                                ),
                              ),
                            ])),

                  ])
                      : Container(
                          width: double.infinity,
                          decoration: const BoxDecoration(
                            color: Color(0XFF1B1D20),
                            borderRadius: BorderRadius.vertical(
                              top: Radius.circular(20.0),
                            ),
                          ),
                          child: Column(
                              mainAxisAlignment: MainAxisAlignment.start,
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                Container(
                                  margin: const EdgeInsets.only(
                                      top: 12.0, left: 20.0, bottom: 24.0),
                                  child: Row(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    crossAxisAlignment:
                                        CrossAxisAlignment.center,
                                    children: <Widget>[
                                      Text(
                                        StringUtil.getCurrentPeriodTitle(
                                            _recordTitle),
                                        textAlign: TextAlign.center,
                                        style: ThemeUtil.mp2
                                            .copyWith(fontSize: 16),
                                      ),
                                      const Spacer(),
                                      EasyTouch(
                                        padding: const EdgeInsets.only(
                                            left: 20,
                                            top: 20,
                                            right: 20,
                                            bottom: 20),
                                        onPressed: () {
                                          _gotoRecordMenstrualPage();
                                        },
                                        child: Row(
                                          mainAxisAlignment:
                                              MainAxisAlignment.start,
                                          crossAxisAlignment:
                                              CrossAxisAlignment.center,
                                          children: [
                                            Image(
                                              image: AssetImage(
                                                  ImageRes.ic_period_edit),
                                              width: 15,
                                              height: 15,
                                            ),
                                            const SizedBox(
                                              width: 4.0,
                                            ),
                                            Text(
                                             StringRes.record,
                                              textAlign: TextAlign.center,
                                              style: ThemeUtil.mp2.copyWith(
                                                  color: const Color(ThemeUtil
                                                      .primaryBlueValue)),
                                            ),
                                          ],
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                                Text(
                                 StringRes.no_symptom_tips,
                                  textAlign: TextAlign.center,
                                  style: ThemeUtil.p2.copyWith(
                                      fontSize: 12,
                                      color: const Color(
                                          ThemeUtil.primaryWhiteValue50)),
                                ),
                                const SizedBox(
                                  height: 120.0,
                                ),
                              ])))
                  : Container(),
            ],
          )),
        ),
      ],
    );
  }

  Widget _buildCategory({
    required List<String> items,
    required List<String> iconPaths,
    required List<bool> isShowLines,
  }) {
    final screenWidth = MediaQuery.of(context).size.width;
    final eachPartWidth = (screenWidth - 20) / 4;
    return  Wrap (
      children: List.generate(items.length, (index) {
        return SizedBox(
          width: eachPartWidth,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Column(
                children: <Widget>[
                  Container(
                    alignment: Alignment.center,
                    margin: const EdgeInsets.only(top: 10, bottom: 10),
                    child: Image(
                      image: AssetImage(iconPaths[index]),
                      width: 48,
                      height: 48,
                    ),
                  ),
                  Container(
                    width: eachPartWidth - 2,
                    alignment: Alignment.center,
                    margin: const EdgeInsets.only(bottom: 30),
                    child: Text(
                      items[index],
                      textAlign: TextAlign.center,
                      style: ThemeUtil.mp2.copyWith(fontSize: 13),
                    ),
                  ),
                ],
              ),
              HorizontalLine(
                  dashedTop: 18,
                  dashedHeight: 28,
                  dashedWidth: 1,
                  color: (isShowLines[index] && index < items.length - 1 && ((index + 1) % 4 != 0)) ? Colors.white24 : Colors.transparent),
            ],
          ),
        );
      }),
    );
  }

  ///获取当前日期的背景
  Widget _getDateTimeBackground(DateTime dateTime,bool isSameDay) {
    if (_menstrualTime <= 0) {
      return const SizedBox( width: 45, height: 45);
    }
    if (_periodDataMap.isNotEmpty && _periodDataMap[DateFormat("yyyy-MM-dd").format(dateTime)] != null) {
      int type = _periodDataMap[DateFormat("yyyy-MM-dd").format(dateTime)]!;
      if (type == 1 || type == 6 || type == 7) {
        return _buildMenstrualPeriod();
      }
      if (type == 3 || type == 4) {
        return _buildEasyPregnancyMiddle();
      }
      if (type == 8) {
        return _buildEasyPregnancyStart();
      }
      if (type == 9) {
        return _buildEasyPregnancyEnd();
      }
      return const SizedBox( width: 45, height: 45);
    }

    int duringType = _isDuringMenstrualPeriodDay(dateTime);
    if (duringType > 0) {
      if(duringType == 1){
        return _buildMenstrualPredictionStart(isSameDay);
      }else if(duringType == 2){
        return _buildMenstrualPredictionMiddle(isSameDay);
      }else if(duringType == 3){
        return _buildMenstrualPredictionEnd(isSameDay);
      }
    }

    if (dateTime.millisecondsSinceEpoch < _menstrualDateTime.millisecondsSinceEpoch) {
      return const SizedBox( width: 45, height: 45);
    }
    if (_isOvulationDay(dateTime)) {
      return _buildEasyPregnancyMiddle();
    }
    int differenceDay = (((dateTime.difference(_menstrualDateTime).inDays).abs()) % widget.cycleValue) + 1;
    if (differenceDay <= _menstrualPeriodDays) {
      return _buildMenstrualPeriod();
    } else if (differenceDay > _menstrualPeriodDays + _follicularPhaseDays && differenceDay <= _menstrualPeriodDays + _follicularPhaseDays + _easyPregnancyDays) {
      int day = differenceDay - _menstrualPeriodDays - _follicularPhaseDays;
      if(_easyPregnancyDays == 10 ){
        if(day == 1 || day == 2 || day == 9 || day == 10){
          return _buildEasyPregnancyStart();
        }else if(day == 3 || day == 4 || day == 7 || day == 8){
          return _buildEasyPregnancyEnd();
        }
      }else if(_easyPregnancyDays == 9){
        if(day == 1 || day == 2 || day == 8 || day == 9){
          return _buildEasyPregnancyStart();
        }else if(day == 3 || day == 4 || day == 6 || day == 7){
          return _buildEasyPregnancyEnd();
        }
      }else if(_easyPregnancyDays == 8){
        if(day == 1 || day == 2 || day == 7 ||day == 8){
          return _buildEasyPregnancyStart();
        }else if(day == 3 || day == 4 || day == 5 || day == 6){
          return _buildEasyPregnancyEnd();
        }
      }else if(_easyPregnancyDays == 7){
        if(day == 1 || day == 2 || day == 7 || day == 6){
          return _buildEasyPregnancyStart();
        }else if(day == 3 || day == 4 || day == 5){
          return _buildEasyPregnancyEnd();
        }
      }else if(_easyPregnancyDays == 6){
        if(day == 1 || day == 6 || day == 5){
          return _buildEasyPregnancyStart();
        }else if(day == 2 || day == 3 || day == 4){
          return _buildEasyPregnancyEnd();
        }
      }else if(_easyPregnancyDays == 5){
        if(day == 1 || day == 5){
          return _buildEasyPregnancyStart();
        }else if(day == 2 || day == 3 || day == 4){
          return _buildEasyPregnancyEnd();
        }
      }else if(_easyPregnancyDays == 4){
        if(day == 1 || day == 4){
          return _buildEasyPregnancyStart();
        }else if(day == 2 || day == 3){
          return _buildEasyPregnancyEnd();
        }
      }
      return _buildEasyPregnancyMiddle();
    } else {
      return const SizedBox( width: 45, height: 45);
    }
  }

  ///经期背景
  Widget _buildMenstrualPeriod() {
    return Container(
      width: 42.5,
      height: 45,
      decoration: BoxDecoration(
        color: const Color(ThemeUtil.primarCalendarMenstruationValue),
        borderRadius: BorderRadius.circular(10.0),
      ),
    );
  }

  ///预测经期开始
  Widget _buildMenstrualPredictionStart(bool isSameDay) {
    return Container(
      width: isSameDay ? 42.5 : double.infinity,
      height: 45,
      decoration: BoxDecoration(
        color: const Color(ThemeUtil.primarCalendarPredictionValue),
        borderRadius: isSameDay ? BorderRadius.circular(10.0) : const BorderRadius.only(topLeft: Radius.circular(10.0), bottomLeft: Radius.circular(10.0)),
      ),
    );
  }

  ///预测经期中间
  Widget _buildMenstrualPredictionMiddle(bool isSameDay) {
    return Container(
      width: isSameDay ? 42.5 : double.infinity,
      height: 45,
      decoration: BoxDecoration(
        color: const Color(ThemeUtil.primarCalendarPredictionValue),
        borderRadius: isSameDay ? BorderRadius.circular(10.0) : BorderRadius.circular(0.0),
      ),
    );
  }

  ///预测经期结束
  Widget _buildMenstrualPredictionEnd(bool isSameDay) {
    return Container(
      width: isSameDay ? 42.5 : double.infinity,
      height: 45,
      decoration: BoxDecoration(
        color: const Color(ThemeUtil.primarCalendarPredictionValue),
        borderRadius: isSameDay ? BorderRadius.circular(10.0) : const BorderRadius.only(topRight: Radius.circular(10.0), bottomRight: Radius.circular(10.0)),
      ),
    );
  }

  ///易孕期开始
  Widget _buildEasyPregnancyStart() {
    return Container(
      alignment: Alignment.bottomCenter,
      width: 42.5,
      height: 45,
      child: Container(
        width: 42.5,
        height: 15,
        decoration: BoxDecoration(
          color: const Color(ThemeUtil.primarPregnancyStartValue),
          borderRadius: BorderRadius.circular(10.0),
        ),
      ),
    );
  }

  ///易孕期中间
  Widget _buildEasyPregnancyMiddle() {
    return Container(
      width: 42.5,
      height: 45,
      decoration: BoxDecoration(
        color: const Color(ThemeUtil.primarPregnancyValue),
        borderRadius: BorderRadius.circular(10.0),
      ),
    );
  }

  ///易孕期结束
  Widget _buildEasyPregnancyEnd() {
    return Container(
      alignment: Alignment.bottomCenter,
      width: 42.5,
      height: 45,
      child: Container(
        width: 42.5,
        height: 35,
        decoration: BoxDecoration(
          color: const Color(ThemeUtil.primarPregnancyEndValue),
          borderRadius: BorderRadius.circular(10.0),
        ),
      ),
    );
  }

  /// 获取指定日期所在月份的天数
  int getDaysInMonth(DateTime date) {
    DateTime nextMonth = DateTime(date.year, date.month + 1, 1);
    DateTime lastDayOfMonth = nextMonth.subtract(const Duration(days: 1));
    return lastDayOfMonth.day;
  }

  String _getRecordDayTitle(DateTime dateTime) {
    if (widget.periodDataMap.isNotEmpty &&
        widget.periodDataMap[DateFormat("yyyy-MM-dd").format(dateTime)] !=
            null) {
      int type =
          widget.periodDataMap[DateFormat("yyyy-MM-dd").format(dateTime)]!;
      if (type == 1 || type == 6 || type == 7) {
        return StringRes.menstrual_period; //月经期
      }
      if (type == 2) {
        return StringRes.follicular_phase; // 卵泡期
      }
      if (type == 3) {
        return StringRes.easy_pregnancy; // 易孕期
      }
      if (type == 4) {
        return StringRes.ovulation_day; // 排卵日
      }
      if (type == 5) {
        return StringRes.luteal_phase; // 黄体期
      }
      if (type == 0) {
        if (_follicularPhaseDays > 0) {
          return StringRes.follicular_phase; // 卵泡期
        } else if (_follicularPhaseDays == 0 && _easyPregnancyDays > 0) {
          return StringRes.easy_pregnancy; // 易孕期
        } else if (_follicularPhaseDays == 0 &&
            _easyPregnancyDays == 0 &&
            _lutealPhaseDays > 0) {
          return StringRes.luteal_phase; // 黄体期
        }
      }
    }
    if (dateTime.millisecondsSinceEpoch < _menstrualDateTime.millisecondsSinceEpoch) {
      return StringRes.other_cycles; //其他经期
    }
    if (_isOvulationDay(dateTime)) {
      return StringRes.ovulation_day; // 排卵日
    }
    DateTime lastMenstrualDate = DateTime.fromMillisecondsSinceEpoch(_menstrualTime);
    if (dateTime.millisecondsSinceEpoch < _menstrualTime) {
      lastMenstrualDate = lastMenstrualDate.subtract(Duration(days: widget.cycleValue));
    }
    int differenceDay = (((dateTime.difference(lastMenstrualDate).inDays).abs()) % widget.cycleValue) + 1;
    if (differenceDay <= _menstrualPeriodDays) {
      return StringRes.menstrual_period; //月经期
    } else if (differenceDay <= _menstrualPeriodDays + _follicularPhaseDays) {
      return StringRes.follicular_phase; // 卵泡期
    } else if (differenceDay <=
        _menstrualPeriodDays + _follicularPhaseDays + _easyPregnancyDays) {
      return StringRes.easy_pregnancy; // 易孕期
    } else if (differenceDay <= _menstrualPeriodDays + _follicularPhaseDays + _easyPregnancyDays + _lutealPhaseDays) {
      return StringRes.luteal_phase; // 黄体期
    }
    return StringRes.other_cycles; //其他经期
  }

  /// 计算两个 DateTime 对象相差的天数
  int _calculateDaysDifference(DateTime startDate, DateTime endDate) {
    return (startDate.difference(endDate).inDays).abs();
  }

  ///判断是否是可以设置月经结束
  bool _isMenstrualPeriodEndDay(DateTime dateTime) {
    if (_isDeleteMenstrual) {
      return false;
    }
    if (_menstrualTime <= 0) {
      return false;
    }
    if (dateTime.millisecondsSinceEpoch >
        DateTime.now().millisecondsSinceEpoch) {
      return false;
    }
    if (dateTime.millisecondsSinceEpoch <
        _menstrualDateTime.millisecondsSinceEpoch) {
      return false;
    }
    DateTime lastDate = _menstrualDateTime;
    if (DateTime.now().difference(lastDate).inDays > widget.cycleValue) {
      lastDate = lastDate.add(Duration(days: widget.cycleValue));
    }
    int differenceDay = dateTime.difference(lastDate).inDays + 1;
    DartLog.i(_tag,
        '判断是否是可以设置月经结束 differenceDay： $differenceDay lastDate: ${DateFormat("yyyy-MM-dd").format(lastDate)}');
    if (differenceDay <= 10 && differenceDay > 1) {
      return true;
    }
    return false;
  }

  ///判断是否是月经期
  bool _isSetMenstrualPeriodDay(DateTime dateTime) {
    if (_menstrualTime <= 0) {
      return false;
    }
    if (_periodDataMap.isNotEmpty &&
        _periodDataMap[DateFormat("yyyy-MM-dd").format(dateTime)] != null) {
      int type = _periodDataMap[DateFormat("yyyy-MM-dd").format(dateTime)]!;
      if (type == 7 || type == 6 || type == 1) {
        return true;
      }
      return false;
    }

    if (dateTime.millisecondsSinceEpoch <
        _menstrualDateTime.millisecondsSinceEpoch) {
      return false;
    }

    int differenceDay =
        (((dateTime.difference(_menstrualDateTime).inDays).abs()) %
                widget.cycleValue) +
            1;
    if (differenceDay <= _menstrualPeriodDays &&
        dateTime.millisecondsSinceEpoch <=
            DateTime.now().millisecondsSinceEpoch) {
      return true;
    }
    return false;
  }

  ///判断是否是月经期
  bool _isMenstrualPeriodDay(DateTime dateTime) {
    if (_menstrualTime <= 0) {
      return false;
    }
    if (_periodDataMap.isNotEmpty &&
        _periodDataMap[DateFormat("yyyy-MM-dd").format(dateTime)] != null) {
      int type = _periodDataMap[DateFormat("yyyy-MM-dd").format(dateTime)]!;
      if (type == 7 || type == 6 || type == 1) {
        return true;
      }
      return false;
    }

    int differenceDay =
        (((dateTime.difference(_menstrualDateTime).inDays).abs()) %
                widget.cycleValue) +
            1;
    if (differenceDay <= _menstrualPeriodDays &&
        dateTime.millisecondsSinceEpoch <=
            DateTime.now().millisecondsSinceEpoch) {
      return true;
    }
    return false;
  }

  ///判断是否是预测经期
  int _isDuringMenstrualPeriodDay(DateTime dateTime) {
    if (_menstrualTime <= 0) {
      return 0;
    }
    int differenceDay = (((dateTime.difference(_menstrualDateTime).inDays).abs()) % widget.cycleValue) + 1;
    if (differenceDay <= _menstrualPeriodDays && dateTime.millisecondsSinceEpoch > DateTime.now().millisecondsSinceEpoch) {
      if (differenceDay == 1) {
        return 1;
      }
      if (differenceDay == _menstrualPeriodDays) {
        return 3;
      }
      return 2;
    }
    return 0;
  }

  ///判断是否是易孕期
  int _isEasyPregnancyDay(DateTime dateTime) {
    if (_periodDataMap.isNotEmpty && _periodDataMap[DateFormat("yyyy-MM-dd").format(dateTime)] != null) {
      int type = _periodDataMap[DateFormat("yyyy-MM-dd").format(dateTime)]!;
      if (type == 3 ||type == 4) {
        return 1;
      }
    }
    int differenceDay = (((dateTime.difference(_menstrualDateTime).inDays).abs()) % widget.cycleValue) + 1;
    if (differenceDay > _menstrualPeriodDays + _follicularPhaseDays && differenceDay <= _menstrualPeriodDays + _follicularPhaseDays + _easyPregnancyDays) {
      return 1;
    }
    return 1;
  }

  ///判断是否是排卵日
  bool _isOvulationDay(DateTime dateTime) {
    if (_menstrualTime <= 0) {
      return false;
    }
    if (!_isShowOvulation) {
      return false;
    }
    if (DateFormat("yyyy-MM-dd").format(_ovulationDateTime) ==
        DateFormat("yyyy-MM-dd").format(dateTime)) {
      return true;
    }
    int differenceDay = _calculateDaysDifference(_ovulationDateTime, dateTime);
    if (differenceDay != 0 && differenceDay % widget.cycleValue == 0) {
      return true;
    }
    return false;
  }

  ///判断是否是排卵日
  bool _isSetOvulationDay(DateTime dateTime) {
    if (dateTime.millisecondsSinceEpoch <
        _menstrualDateTime.millisecondsSinceEpoch) {
      return false;
    }
    if (_menstrualTime <= 0) {
      return false;
    }
    if (!_isShowOvulation) {
      return false;
    }
    if (DateFormat("yyyy-MM-dd").format(_ovulationDateTime) ==
        DateFormat("yyyy-MM-dd").format(dateTime)) {
      return true;
    }
    int differenceDay = _calculateDaysDifference(_ovulationDateTime, dateTime);
    if (differenceDay != 0 && differenceDay % widget.cycleValue == 0) {
      return true;
    }
    return false;
  }

  ///判断是否同一天
  bool _isSameDay(DateTime date1, DateTime date2) {
    return date1.year == date2.year &&
        date1.month == date2.month &&
        date1.day == date2.day;
  }

  ///判断是否有经期记录
  bool _isRecordMenstrual(DateTime dateTime) {
    for (MenstrualRecord record in _menstrualRecordList) {
      if (record.day == DateFormat("yyyy-MM-dd").format(dateTime)) {
        return true;
      }
    }
    return false;
  }

  ///判断是否显示经期开始
  bool _isMenstrualStartDay(DateTime dateTime) {
    if (_menstrualTime <= 0) {
      return false;
    }
    if (dateTime.millisecondsSinceEpoch >
        DateTime.now().millisecondsSinceEpoch) {
      return false;
    }
    if (_periodDataMap.isNotEmpty &&
        _periodDataMap[DateFormat("yyyy-MM-dd").format(dateTime)] != null) {
      int type = _periodDataMap[DateFormat("yyyy-MM-dd").format(dateTime)]!;
      if (type == 6) {
        return true;
      }
      return false;
    }
    if (dateTime.millisecondsSinceEpoch < _menstrualTime) {
      return false;
    }
    int differenceDay =
        (((dateTime.difference(_menstrualDateTime).inDays).abs()) %
                widget.cycleValue) +
            1;
    if (differenceDay == 1) {
      return true; //月经开始时间
    }
    return false;
  }

  ///判断是否显示经期结束
  bool _isMenstrualEndDay(DateTime dateTime) {
    if (_menstrualTime <= 0) {
      return false;
    }
    if (dateTime.millisecondsSinceEpoch >
        DateTime.now().millisecondsSinceEpoch) {
      return false;
    }

    if (_periodDataMap.isNotEmpty &&
        _periodDataMap[DateFormat("yyyy-MM-dd").format(dateTime)] != null) {
      int type = _periodDataMap[DateFormat("yyyy-MM-dd").format(dateTime)]!;
      if (type == 7) {
        return true;
      }
      return false;
    }
    if (dateTime.millisecondsSinceEpoch < _menstrualTime) {
      return false;
    }
    int differenceDay =
        (((dateTime.difference(_menstrualDateTime).inDays).abs()) %
                widget.cycleValue) +
            1;
    if (differenceDay == _menstrualPeriodDays) {
      return true; //月经结束时间
    }
    return false;
  }

  ///判断是否设置经期开始
  bool _isEditMenstrualStartDay(DateTime dateTime) {
    if (_isDeleteMenstrual) {
      return false;
    }
    if (_menstrualTime <= 0) {
      return false;
    }
    if (dateTime.millisecondsSinceEpoch > DateTime.now().millisecondsSinceEpoch) {
      return false;
    }

    if (DateTime.now().difference(dateTime).inDays > widget.cycleValue) {
      return false;
    }

    if (_periodDataMap.isNotEmpty && _periodDataMap[DateFormat("yyyy-MM-dd").format(dateTime)] != null) {
      int type = _periodDataMap[DateFormat("yyyy-MM-dd").format(dateTime)]!;
      if (type == 6) {
        if (dateTime.millisecondsSinceEpoch < _menstrualDateTime.millisecondsSinceEpoch) {
          return false;
        }
        return true;
      }
      return false;
    }

    int differenceDay =
        (((dateTime.difference(_menstrualDateTime).inDays).abs()) %
                widget.cycleValue) +
            1;
    if (differenceDay == 1) {
      return true; //月经开始时间
    }
    return false;
  }

  ///判断是否设置经期结束
  bool _isEditMenstrualEndDay(DateTime dateTime) {
    if (_menstrualTime <= 0) {
      return false;
    }
    if (dateTime.millisecondsSinceEpoch >
        DateTime.now().millisecondsSinceEpoch) {
      return false;
    }

    if (DateTime.now().difference(dateTime).inDays > widget.cycleValue) {
      return false;
    }

    if (_periodDataMap.isNotEmpty &&
        _periodDataMap[DateFormat("yyyy-MM-dd").format(dateTime)] != null) {
      int type = _periodDataMap[DateFormat("yyyy-MM-dd").format(dateTime)]!;
      if (type == 7) {
        if (dateTime.millisecondsSinceEpoch <
            _menstrualDateTime.millisecondsSinceEpoch) {
          return false;
        }
        return true;
      }
      return false;
    }

    int differenceDay =
        (((dateTime.difference(_menstrualDateTime).inDays).abs()) %
                widget.cycleValue) +
            1;
    if (differenceDay == _menstrualPeriodDays) {
      return true; //月经结束时间
    }
    return false;
  }

  ///设置经期状态(开始或者结束)
  void _setMenstrualStatus(DateTime dateTime) {
    if (dateTime.millisecondsSinceEpoch >
        DateTime.now().millisecondsSinceEpoch) {
      _isShowMenstrualStatus = false;
      return;
    }
    if (dateTime.millisecondsSinceEpoch <
        DateTime.now()
            .subtract(const Duration(days: 30))
            .millisecondsSinceEpoch) {
      _isShowMenstrualStatus = false;
      return;
    }
    _isShowMenstrualStatus = true;
    if (_isEditMenstrualEndDay(dateTime)) {
      _isMenstrualStatus = true;
      _isMenstrualSelect = true;
      return;
    }
    if (_isEditMenstrualStartDay(dateTime)) {
      _isMenstrualStatus = false;
      _isMenstrualSelect = true;
      return;
    }
    if (_isMenstrualPeriodEndDay(dateTime)) {
      _isMenstrualStatus = true;
      _isMenstrualSelect = false;
      return;
    }
    _isMenstrualStatus = false;
    _isMenstrualSelect = false;
  }

  ///跳转到设置周期记录界面
  _gotoRecordMenstrualPage() {
    Map<String, dynamic> dataMap = <String, dynamic>{};
    dataMap['flowIndex'] = _flowIndex;
    dataMap['colorIndex'] = _colorIndex;
    dataMap['dysmenorrheaIndex'] = _dysmenorrheaIndex;
    dataMap['symptomSelected'] = _symptomSelected;
    dataMap['leucorrheaIndex'] = _leucorrheaIndex;
    dataMap['moodIndex'] = _moodIndex;
    dataMap['ovulationIndex'] = _ovulationIndex;
    dataMap['sexIndex'] = _sexIndex;
    dataMap['notes'] = _notes;
    DartLog.i(_tag, 'dataMap：${dataMap.toString()}');
    //跳转到记录经期页面
    Get.toNamed(PageIndex.recordMenstrualPage, arguments: {
      "userId": widget.userId,
      "recordTitle": _recordTitle,
      "recordDay": DateFormat("yyyy-MM-dd").format(_recordDateTime),
      "recordDayTitle": S.isCN()
          ? DateFormat("yyyy-MM-dd").format(_recordDateTime)
          : "${StringUtil.getTodayMonth(_recordDateTime.month)} ${_recordDateTime.day > 9 ? _recordDateTime.day : '0${_recordDateTime.day}'}, ${_recordDateTime.year}",
      "isMenstrualRecord": _isMenstrualPeriodDay(_recordDateTime),
      "recordMap": dataMap,
    });
  }

  /// 设置点击周期设置
  void _setMenstrualClick() {
    if (_isEditMenstrualEndDay(_recordDateTime)) {
      ToastUtil.show(StringRes.menstruation_end_select_tips);
      return;
    }
    if (_isEditMenstrualStartDay(_recordDateTime)) { //取消当前经期,都设置成卵泡期
      if(_periodDataMap.isNotEmpty){
        int differenceDay = DateTime.now().add(Duration(days: widget.cycleValue)).difference(_recordDateTime).inDays;
        DartLog.i(_tag, '_recordDateTime和今天加一个周期相差多少天 differenceDay$differenceDay');
        for (int i = 0; i < differenceDay; i++) {
          DateTime dateTime = _recordDateTime.add(Duration(days: i));
          _periodDataMap.remove(DateFormat("yyyy-MM-dd").format(dateTime));
        }
      }
      DateTime lastDate = _menstrualDateTime;
      if (DateTime.now().difference(lastDate).inDays > widget.cycleValue) {
        lastDate = lastDate.add(Duration(days: widget.cycleValue));
      }
      int differenceDay = _recordDateTime.difference(lastDate).inDays + 1;
      DartLog.i(_tag, '_recordDateTime和第一次月经相差多少天 differenceDay$differenceDay');
      for (int i = 0; i < _menstrualPeriodDays; i++) {
        DateTime dateTime = lastDate.add(Duration(days: i));
        _periodDataMap[DateFormat("yyyy-MM-dd").format(dateTime)] = 2; // 卵泡期
      }
      DartLog.i(_tag, '今天和第一次月经 _periodDataMap${_periodDataMap.toString()}');
      Map<String, dynamic> mainDataMap = <String, dynamic>{};
      if (_periodDataMap.isNotEmpty) {
        mainDataMap['periodDataMap'] = _periodDataMap;
        EventBusUtil.getInstance().fire(DataEvent(HealthDataType.REFRESH_CURRENT_HEALTH_DATA, mainDataMap));
        _saveHistoryListToLocal();
      }
      _setMenstrualStatus(_recordDateTime);
      setState(() {});
      _isDeleteMenstrual = true;
      return;
    }
    if (_isMenstrualPeriodEndDay(_recordDateTime)) { //月经周期内设置
      if(_periodDataMap.isNotEmpty){
        int differenceDay = DateTime.now().add(Duration(days: widget.cycleValue)).difference(_recordDateTime).inDays;
        DartLog.i(_tag, '_recordDateTime和今天加一个周期相差多少天 differenceDay$differenceDay');
        for (int i = 0; i < differenceDay; i++) {
          DateTime dateTime = _recordDateTime.add(Duration(days: i));
          _periodDataMap.remove(DateFormat("yyyy-MM-dd").format(dateTime));
        }
        DartLog.i(_tag, '在月经周期内设置 _periodDataMap${_periodDataMap.toString()}');
      }
      DateTime lastDate = _menstrualDateTime;
      if (DateTime.now().difference(lastDate).inDays > widget.cycleValue) {
        lastDate = lastDate.add(Duration(days: widget.cycleValue));
      }
      int differenceDay = _recordDateTime.difference(lastDate).inDays + 1;
      DartLog.i(_tag, '_recordDateTime和第一次月经相差多少天 differenceDay$differenceDay');
      if(differenceDay < _menstrualPeriodDays){
        for (int i = 0; i < _menstrualPeriodDays; i++) {
          DateTime dateTime = lastDate.add(Duration(days: i));
          if (i == 0) {
            _periodDataMap[DateFormat("yyyy-MM-dd").format(dateTime)] = 6; // 月经开始
          } else if (i == differenceDay - 1) {
            _periodDataMap[DateFormat("yyyy-MM-dd").format(dateTime)] = 7; // 月经结束
          } else if (i > 0 && i < differenceDay - 1) {
            _periodDataMap[DateFormat("yyyy-MM-dd").format(dateTime)] = 1; // 月经期
          }else{
            _periodDataMap[DateFormat("yyyy-MM-dd").format(dateTime)] = 2; // 卵泡期
          }
        }
      }else{
        DartLog.i(_tag, '_recordDateTime和第一次月经,经期延迟结束');
        for (int i = 0; i < differenceDay; i++) {
          DateTime dateTime = lastDate.add(Duration(days: i));
          if (i == 0) {
            _periodDataMap[DateFormat("yyyy-MM-dd").format(dateTime)] = 6; // 月经开始
          } else if (i == differenceDay - 1) {
            _periodDataMap[DateFormat("yyyy-MM-dd").format(dateTime)] = 7; // 月经结束
          } else if (i > 0 && i < differenceDay - 1) {
            _periodDataMap[DateFormat("yyyy-MM-dd").format(dateTime)] = 1; // 月经期
          }
        }
      }
      DartLog.i(_tag, '今天和第一次月经 _periodDataMap${_periodDataMap.toString()}');
      Map<String, dynamic> mainDataMap = <String, dynamic>{};
      if (_periodDataMap.isNotEmpty) {
        mainDataMap['periodDataMap'] = _periodDataMap;
        EventBusUtil.getInstance().fire(DataEvent(HealthDataType.REFRESH_CURRENT_HEALTH_DATA, mainDataMap));
        _saveHistoryListToLocal();
      }
      _setMenstrualStatus(_recordDateTime);
      setState(() {});
      return;
    }
    if(_isDeleteMenstrual){
      int differenceDay = DateTime.now().add(Duration(days: widget.cycleValue)).difference(_recordDateTime).inDays;
      DartLog.i(_tag, '_recordDateTime和今天加一个周期相差多少天 differenceDay$differenceDay');
      for (int i = 0; i < differenceDay; i++) {
        DateTime dateTime = _recordDateTime.add(Duration(days: i));
        _periodDataMap.remove(DateFormat("yyyy-MM-dd").format(dateTime));
      }
    }else{
      if(_recordDateTime.millisecondsSinceEpoch < _menstrualTime){
        if(_periodDataMap.isNotEmpty){
          int differenceDay = DateTime.now().add(Duration(days: widget.cycleValue)).difference(_recordDateTime).inDays;
          DartLog.i(_tag, '_recordDateTime和今天加一个周期相差多少天 differenceDay$differenceDay');
          for (int i = 0; i < differenceDay; i++) {
            DateTime dateTime = _recordDateTime.add(Duration(days: i));
            _periodDataMap.remove(DateFormat("yyyy-MM-dd").format(dateTime));
          }
        }else{
          _periodDataMap.clear();
        }
      }else{
        int differenceDay = _recordDateTime.difference(_menstrualDateTime).inDays;
        DartLog.i(_tag, '_recordDateTime和_menstrualDateTime相差多少天 differenceDay$differenceDay');
        for (int i = 0; i < differenceDay; i++) {
          DateTime dateTime = _menstrualDateTime.add(Duration(days: i));
          _periodDataMap[DateFormat("yyyy-MM-dd").format(dateTime)] = _getDateTimeFemaleCycle(dateTime);
        }
      }
    }
    DartLog.i(_tag, '今天和第一次月经 _periodDataMap${_periodDataMap.toString()}');
    _menstrualDateTime = _recordDateTime;
    _menstrualTime = _menstrualDateTime.millisecondsSinceEpoch;
    _isDeleteMenstrual = false;
    updateWomanHealthData();
  }

  ///更新女性健康数据
  void updateWomanHealthData() {
    Map<String, dynamic> mainDataMap = <String, dynamic>{};
    mainDataMap['menstrualTime'] = _menstrualTime;
    if (_periodDataMap.isNotEmpty) {
      mainDataMap['periodDataMap'] = _periodDataMap;
      _saveHistoryListToLocal();
    }else{
      mainDataMap['periodEmptyMap'] = "Empty";
      _saveEmptyHistoryListToLocal();
    }
    var timeString = DateFormat("yyyy-MM-dd")
        .format(DateTime.fromMillisecondsSinceEpoch(_menstrualTime));
    Map<String, dynamic> dataMap = <String, dynamic>{};
    dataMap['health_menstrual_time'] = timeString;
    dataMap['health_cycle_value'] = widget.cycleValue;
    dataMap['health_period_length'] = _menstrualPeriodDays;
    dataMap['health_regularly'] = widget.regularly;
    dataMap['health_tracking'] = widget.tracking;
    Native.setWomenHealthData(dataMap);
    _setMenstrualStatus(_recordDateTime);
    _initCalculationPeriodData();
    setState(() {});
    EventBusUtil.getInstance().fire(
        DataEvent(HealthDataType.REFRESH_CURRENT_HEALTH_DATA, mainDataMap));
  }

  ///获取dateTime属于的周期(0:未设置 1:月经期 2:卵泡期 3:易孕期(排卵期) 4:排卵日 5:黄体期,6,月经开始时间,7月经结束时间，8:易孕期低 9:易孕期中)
  int _getDateTimeFemaleCycle(DateTime dateTime) {
    int differenceDay = (dateTime.difference(_menstrualDateTime).inDays % widget.cycleValue) + 1;
    if (differenceDay <= _menstrualPeriodDays) {
      if (differenceDay == 1) {
        return 6; // 月经开始
      }
      if (differenceDay == _menstrualPeriodDays) {
        return 7; // 月经结束
      }
      return 1; // 月经期
    } else if (differenceDay <= _menstrualPeriodDays + _follicularPhaseDays) {
      return 2; // 卵泡期
    } else if (differenceDay <= _menstrualPeriodDays + _follicularPhaseDays + _easyPregnancyDays) {
      if (differenceDay == _menstrualPeriodDays + _follicularPhaseDays + _preFertileLength + 1) {
        return 4; //排卵日
      }
      int day = differenceDay - _menstrualPeriodDays - _follicularPhaseDays;
      if(_easyPregnancyDays == 10 ){
        if(day == 1 || day == 2 || day == 9 || day == 10){
          return 8;
        }else if(day == 3 || day == 4 || day == 7 || day == 8){
          return 9;
        }
      }else if(_easyPregnancyDays == 9){
        if(day == 1 || day == 2 || day == 8 || day == 9){
          return 8;
        }else if(day == 3 || day == 4 || day == 6 || day == 7){
          return 9;
        }
      }else if(_easyPregnancyDays == 8){
        if(day == 1 || day == 2 || day == 7 ||day == 8){
          return 8;
        }else if(day == 3 || day == 4 || day == 5 || day == 6){
          return 9;
        }
      }else if(_easyPregnancyDays == 7){
        if(day == 1 || day == 2 || day == 7 || day == 6){
          return 8;
        }else if(day == 3 || day == 4 || day == 5){
          return 9;
        }
      }else if(_easyPregnancyDays == 6){
        if(day == 1 || day == 6 || day == 5){
          return 8;
        }else if(day == 2 || day == 3 || day == 4){
          return 9;
        }
      }else if(_easyPregnancyDays == 5){
        if(day == 1 || day == 5){
          return 8;
        }else if(day == 2 || day == 3 || day == 4){
          return 9;
        }
      }else if(_easyPregnancyDays == 4){
        if(day == 1 || day == 4){
          return 8;
        }else if(day == 2 || day == 3){
          return 9;
        }
      }

      return 3; // 易孕期
    }
    return 5; // 黄体期
  }

  ///保存经期历史列表到本地
  _saveHistoryListToLocal() {
    String historyListJson = jsonEncode(_periodDataMap);
    Native.writeHealthHistoryList(historyListJson);
    DartLog.i(_tag, "History 列表已保存到本地: $historyListJson");
  }

  ///保存经期历史列表到本地
  _saveEmptyHistoryListToLocal() {
    Native.writeHealthHistoryList("");
    DartLog.i(_tag, "History 列表已保存到本地: 空字符串");
  }
}
